<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<title>FNST-在线笔试系统</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" href="../../layui/css/layui.css" media="all">

		<style>
			.timer {
				text-align: center;
				color: #1E9FFF;
				font-size: 24px;
				font-family:"楷体";
			}
		</style>
	</head>

	<body onbeforeunload="return myFunction()">
		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
			<legend>FNST-在线笔试系统</legend>
		</fieldset>
		<div style="padding: 20px; background-color: #F2F2F2;">
			<div class="layui-row layui-col-space15">
				<div class="layui-col-md12">
					<div class="layui-card">
						<div class="layui-card-header">笔试答题</div>
						<div class="timer">
							     FNST在线笔试，当前答题者：<span id="username"></span>
						</div>
						<div class="timer" id="timer">

						</div>
						<br />

						<hr class="layui-bg-orange">
						<div class="layui-card-body">
							<div id="EXAM">
							</div>
							<input type="hidden" id="listid" />
							<div class="site-demo-button" style="margin-top: 40px; text-align: right;">
								<button class="layui-btn site-demo-layedit" style="" id="commit">提交题目</button>
							</div>

						</div>
					</div>
				</div>
			</div>
		</div>
		<script src="../../layui/layui.js"></script>
		<script src="../js/common.js"></script>
		<script src="../../js/sockjs.min.js"></script>
		<script src="../../js/stomp.min.js"></script>
		<script>
			var minute,
				second;
			var maxtime = 60 * 60; //一个小时，按秒计算，自己调整!  
			var list = [];
			var listmsg = [];
			var listVal = [];
			var stompClient;
			var serverUrl = host() + "/websocket";
			var room; //频道号
			var websocket = null;
			var userid = localStorage.getItem("userid");
			//websocket连接
			function conectWebSocket(room, serverUrl) {
				var socket = new SockJS(serverUrl);
				this.stompClient = Stomp.over(socket);
				var that = this;
				this.stompClient.connect({}, function(frame) {
					that.stompClient.subscribe('/topic/' + room, function(txt) {});
				});
			}

			function disconnect() {
				//断开连接的方法
				if(this.stompClient !== undefined) {
					this.stompClient.disconnect();
					layer.alert("Disconnected");
				} else {
					layer.alert("当前没有连接websocket")
				}
				this.stompClient = undefined;
			}

			//发送消息
			function sendMessage(msg, questionid) {
				var socketMsg = {
					msg: msg,
					toUser: userid
				};
				this.stompClient.send(
					'/app/chat', {},
					JSON.stringify({
						'room': userid,
						'type': "1", //1,2
						'content': msg,
						'userId': userid, //小明
						'questionId': questionid, //题目1
						'createTime': "",
					})
				);

			}

			layui.use('layedit', function() {
				var $ = layui.jquery;
				var layedit = layui.layedit;

				var active = {
					setTop: function() {
						var that = this;
						//多窗口模式，层叠置顶
						layer.open({
							type: 2 //此处以iframe举例
								,
							title: '当你选择该窗体时，即会在最顶端',
							area: ['390px', '260px'],
							shade: 0,
							maxmin: true,
							offset: [ //为了演示，随机坐标
								Math.random() * ($(window).height() - 300), Math.random() * ($(window).width() - 390)
							],
							content: '//layer.layui.com/test/settop.html',
							btn: ['继续弹出', '全部关闭'] //只是为了演示
								,
							yes: function() {
								$(that).click();
							},
							btn2: function() {
									layer.closeAll();
								}

								,
							zIndex: layer.zIndex //重点1
								,
							success: function(layero) {
								layer.setTop(layero); //重点2
							}
						});
					},
					notice: function() {
						layer.open({
							type: 1,
							title: false,
							closeBtn: false,
							area: '300px;',
							shade: 0.8,
							id: 'LAY_layuipro',
							btnAlign: 'c',
							moveType: 1,
							content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">答题结束，题目已提交</div>'
						});
					}
				};

				var timer = null;
				var timer2 = null;
				if(localStorage.getItem("maxtime") != null) {
					maxtime = localStorage.getItem("maxtime");
                    localStorage.removeItem("maxtime");
				}
				timer = setInterval(function() {
					if(maxtime >= 0) {
						minutes = Math.floor(maxtime / 60);
						seconds = Math.floor(maxtime % 60);
						msg = "距离结束还有" + minutes + "分" + seconds + "秒";
						document.all["timer"].innerHTML = msg;
						if(maxtime == 5 * 60) alert("还剩5分钟");
						--maxtime;
					} else {
						clearInterval(timer);
						clearInterval(timer2);
						$.ajax({
							type: "get",
							url: host() + "/endTest",
							data: {
								token: localStorage.getItem("token2")
							},
							async: false,
							success: function(res) {
								maxtime = 60*60;
								localStorage.removeItem("maxtime");
								for(var i = 0; i < listmsg.length; i++) {
								    listmsg[i]="";
								    listVal[i]="";
									localStorage.removeItem(listmsg[i]);
								}
								localStorage.removeItem('token2');
								$("#commit").remove();
								document.onkeydown = function(e) {
									var ev = window.event || e;
									var code = ev.keyCode || ev.which;
									if(code == 116) {
										ev.keyCode ? ev.keyCode = 0 : ev.which = 0;
										cancelBubble = true;
										return false;
									}
								} //禁止f5刷新
								document.oncontextmenu = function() {
									return false
								};
							}
						});
						var othis = $(this);
						active["notice"] ? active["notice"].call(this, othis) : '';
					}
				}, 1000);

				//构建一个默认的编辑器
				$("#username").text(localStorage.getItem("username"));
				$.ajax({
					type: 'get',
					url: host() + "/getSelfQuestions",
					data: {
						token: localStorage.token2,
					},
					dataType: 'json',
					async: false,
					success: function(msg) {
						var exam = $("#EXAM");
						for(var i = 0; i < msg.data.length; i++) {
							var j = i + 1;
							var h = '<div class="layui-form-item "><div class="layui-form-item "><span>第' + j + '题：</span><span class="question"id="quesion' + j + '">' + msg.data[i].subject + '</span></div></div><hr class="layui-bg-grey"><div class="layui-form-item"><span>答题：</span><textarea class="layui-textarea answer" id="' + msg.data[i].id + '" style="height: 300px;"></textarea><hr class="layui-bg-red"></div>';
							exam.append(h);
							listmsg.push(msg.data[i].id);
							list.push(layedit.build(msg.data[i].id, {
								tool: ['strong' //加粗
									, 'italic', 'underline', 'del', '|', 'left', 'center', 'right'
								]
							}));
							layedit.setContent(list[i], localStorage.getItem(listmsg[i]));
                            localStorage.removeItem(listmsg[i]);
						}
					},
					error: function(msg) {}
				})

				timer2 = setInterval(function() {
					for(var i = 0; i < listmsg.length; i++) {
						if(listVal[i] != layedit.getContent(list[i])) {
							sendMessage(layedit.getContent(list[i]), listmsg[i]);
							listVal[i] = layedit.getContent(list[i]);
						}
					}

				}, 1000)

				$("#commit").on('click', function() {
					$.ajax({
						type: "get",
						url: host() + "/endTest",
						data: {
							token: localStorage.getItem("token2")
						},
						async: false,
						success: function(res) {
						    maxtime=60*60;

							localStorage.removeItem('maxtime');
							for(var i = 0; i < listmsg.length; i++) {
							    listmsg[i]="";
                                listVal[i]="";
								localStorage.removeItem(listmsg[i]);
							}
							localStorage.removeItem('token2');
							$("#commit").remove();
							clearInterval(timer);
							clearInterval(timer2);
							document.onkeydown = function(e) {
									var ev = window.event || e;
									var code = ev.keyCode || ev.which;
									if(code == 116) {
										ev.keyCode ? ev.keyCode = 0 : ev.which = 0;
										cancelBubble = true;
										return false;
									}
								} //禁止f5刷新
								document.oncontextmenu = function() {
									return false
								};
						}
					});
					var othis = $(this);
					active["notice"] ? active["notice"].call(this, othis) : '';
				});

			});

			function myFunction() {
			    if(maxtime!=3600){
                    localStorage.setItem("maxtime", maxtime);
				}

				for(var i = 0; i < listmsg.length; i++) {
			        if(listVal[i]!=""){
                        localStorage.setItem(listmsg[i], listVal[i]);
					}
				}
			}
			window.onload = function() {
				this.conectWebSocket(userid, serverUrl);
			}
		</script>
	</body>

</html>